#!/bin/bash
# 2021.10.09
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
mail(){
        SMTP="smtp.ezcdn.cn 25"
        SMTP_DOMAIN="sub.wsztest.com"
        FROM="smonitor@sub.wsztest.com"
        RCPTTO="yunwei.list@cndns.com"
        USERNAME="c21vbml0b3JAc3ViLndzenRlc3QuY29t"
        PASSWORD="UzB1RjlxWDJZVQ=="
        LOCAL_IP=`ifconfig|grep Bcast|awk -F: '{print $2}'|awk -F " " '{print $1}'|head -1`
        LOCAL_NAME=`uname -n`
        (sleep 10;for i in "ehlo $SMTP_DOMAIN" "AUTH LOGIN" "$USERNAME" "$PASSWORD" "MAIL FROM:<$FROM>" "RCPT TO:<$RCPTTO>" "DATA";do
                /bin/echo $i
                sleep 4
        done
        /bin/echo "Subject:$1 $LOCAL_IP"
        /bin/echo "From:<$FROM>"
        /bin/echo "To:<$RCPTTO>"
        /bin/echo ""
        /bin/echo -e "$LOCAL_NAME\n$LOCAL_IP\n$2"
        /bin/echo "."
        sleep 2
        /bin/echo "quit" )|telnet $SMTP
}

if [ ! -f /root/sec_check.sh ];then
    mail "/root/sec_check.sh does not exist" "/root/sec_check.sh does not exist"
    exit
fi

if [ `ps axu|grep 'sec_check.sh'|grep -v grep|wc -l` != 0 ];then
    rm -f /root/secud_status.txt
    exit
fi

check_secud()
{
secud_status="/root/secud_status.txt"
#Detect three times. If they are all closed, turn them on
if [ -f $secud_status ];then
    num=`cat $secud_status`
    if [ "$num" == "1" ];then
        if [ `ps axu|grep 'sec_check.sh'|grep -v grep|wc -l` == 0 ];then
            echo "2" > $secud_status
        fi
    elif [ "$num" == "2" ];then
        if [ `ps axu|grep 'sec_check.sh'|grep -v grep|wc -l` == 0 ];then
            echo "3" > $secud_status
        fi
    elif [ "$num" == "3" ];then
        /etc/init.d/secud start
        if [ "$?" -ne "0"  ];then
            mail "secud Service startup failed" "secud Service startup failed,please check the server now!"
        else
            rm -f $secud_status
        fi
    else
        /etc/init.d/secud start
        rm -f $secud_status
    fi     
else
    if [ `ps axu|grep 'sec_check.sh'|grep -v grep|wc -l` == 0 ];then
        echo "1" > $secud_status
    fi
fi       
}

check_secud
